/*******************************************************************************
 * Copyright (c) 2018.
 * This file was written by Fancyears·Milos·Malvis @connor. Any question/bug you can't post to 1243093366@qq.com.
 * ALL RIGHTS RESERVED.
 ******************************************************************************/
package org.fancyears.commom;

import javax.swing.JDialog;
import javax.swing.JFrame;

import org.fancyears.helper.LocationHeklper;

import lombok.Data;

/**
 * 窗口初始化类，实现{@link Initializer}接口的规范，可以直接继承，但是需要重写init方法和createContents方法
 * 
 * <p>
 * 如需要自定义show，需要重写show()方法，默认的show()方法是居中显示
 * 
 * 
 * @author: Fancyears·Milos·Malvis
 * @CreateDate: 2018年12月3日 下午5:07:11
 * @Description: 基础初始化器
 */
@Data
public abstract class Initialization implements Initializer {
	/**
	 * 窗口
	 */
	protected JFrame jf;
	/**
	 * 对话框
	 */
	protected JDialog jd;
	/**
	 * 设定是否强制使用JDialog
	 * <p>
	 * 如果设置了为true， 则只显示Dialog，否则根据JFrame是否为null显示JFrame
	 * 如果forceUsingDialog为false，且JFrame和JDialog都不为null，则JFrame和JDialog都将显示出来
	 */
	protected boolean forceUsingDialog = false;

	/**
	 * 设定自定义显示功能，如果需要自定义显示功能，则设置为true并重写show方法，否则将什么也不显示
	 */
	protected boolean customShow = false;

	public Initialization() {

	}

	@Override
	public void run() {
		try {
			init();
			createContents();
			executeShow();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 默认的显示窗口方法
	 * <p>
	 * 默认的显示请看{@link Initialization#forceUsingDialog}
	 * 
	 * @throws Exception
	 */
	protected void defualtShow() throws Exception {
		boolean isUse = false;
		if (forceUsingDialog) {
			if (null == jd) {
				throw new Exception("JDialog 未初始化");
			}
			showDialog();
			return;
		}
		if (null == jf) {
			isUse = true;
		} else {
			showFrame();
		}
		if (null == jd) {
			if (isUse)
				throw new Exception("Jframe 未初始化");
		} else {
			showDialog();
		}

	}

	/**
	 * 显示JDialog弹窗，Dialog弹窗默认是居中显示，关闭后即dispose
	 * 
	 * @throws Exception
	 */
	protected void showDialog() throws Exception {
		LocationHeklper.setToCenter(jd);
		jd.setVisible(true);
		jd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
	}

	/**
	 * 显示JFrane窗口，Frame窗口默认是居中显示，关闭后即dispose
	 * 
	 * @throws Exception
	 */
	protected void showFrame() throws Exception {
		LocationHeklper.setToCenter(jf);
		jf.setVisible(true);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	/**
	 * 根据customShow执行defualtShow()方法或者是show()方法
	 * 
	 * @throws Exception
	 */
	protected void executeShow() throws Exception {
		if (!customShow) {
			defualtShow();
		} else {
			show();
		}
	}
}
